import { SingletonBase } from "./SingletonBase";
import { BaseUI, UIClass } from "../Base/BaseUI";
import { ResManager, SaveType, RetHander } from "./ResManager";
import { resLoader } from "../res/ResLoader";

export class UIManager extends SingletonBase{
    private m_uiRoot:cc.Node=null;
    private m_uiList:BaseUI[]=[];

    constructor(){
        super();
        this.m_uiRoot=cc.find("Canvas");
    }

    private openUI<T extends BaseUI>(uiClass:UIClass<T>,zOrder?:number,callback?:Function,onProgress?: Function, ...args: any[]){
        if(this.getUI(uiClass)){
            return;
        }
        ResManager.getInstance().loadRes(uiClass.getUrl(),cc.Prefab,(ret:RetHander)=>{
            if(ret.m_err){
                cc.log(ret.m_err);
                return;
            }
            if(this.getUI(uiClass)){
                return;
            }
            let uiNode:cc.Node=ret.m_data[0];
            uiNode.parent=this.m_uiRoot;
            if(zOrder)uiNode.zIndex=zOrder;
            let ui=uiNode.getComponent(uiClass) as BaseUI;
            ui.tag=uiClass;
            ui.autoReleaseRes({ url: resLoader.getResKeyByUrl(uiClass.getUrl(), cc.Prefab), type: cc.Prefab, use:`ui_${cc.js.getClassName(ui)}` }, false);
            this.m_uiList.push(ui);
            console.log(ui);
            callback&&callback(ui,args);
        },{saveType:SaveType.UI,onProgress:onProgress});
    }

    public closeUI<T extends BaseUI>(uiClass:UIClass<T>){
        for(let i=0;i<this.m_uiList.length;++i){
            if(this.m_uiList[i].tag===uiClass){
                this.m_uiList[i].node.destroy();
                this.m_uiList.splice(i,1);
                return;
            }
        }
    }

    public showUI<T extends BaseUI>(uiClass:UIClass<T>,callback?:Function,zOrder?:number,onProgress?: Function,...args: any[]){
        let ui=this.getUI(uiClass);
        if(ui){
            ui.node.active=true;
            ui.onShow();
            callback&&callback(ui);
        }
        else{
            this.openUI(uiClass,zOrder,()=>{
                let ui=this.getUI(uiClass);
                ui.onShow();
                callback&&callback(ui);
            },onProgress,args);
        }
    }

    public hideUI<T extends BaseUI>(uiClass:UIClass<T>,isDes:boolean=false){
        let ui=this.getUI(uiClass);
        console.log(ui,isDes);
        if(ui){
            if(isDes)ui.node.destroy();
            else ui.node.active=false;
        }
    }

    private getUI<T extends BaseUI>(uiClass:UIClass<T>):BaseUI{
        for(let i=0;i<this.m_uiList.length;i++){
            if(this.m_uiList[i].tag===uiClass){
                return this.m_uiList[i];
            }
        }
        return null;
    }
}
